//
//  MyQRViewController.m
//  Moviefans
//
//  Created by jack on 2018/10/8.
//  Copyright © 2018年 __Mycompany. All rights reserved.
//

#import "AddFriendViewController.h"

@interface AddFriendViewController ()
@property (strong,nonatomic)UIImageView *bgView;
@property (strong,nonatomic)UIImageView * QRImage;
@property (strong,nonatomic)UIButton * CopyContent;
@property (strong,nonatomic)UILabel * SecretKey;
@property (strong,nonatomic)UILabel * scannQR;

@property (strong,nonatomic)UIImageView * store;
@property (strong,nonatomic)UILabel * titleView;
//shoukuan_baocun
@end

@implementation AddFriendViewController

- (void)rightBarButton {
    UIButton *saveBar = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBar.frame = CGRectMake(SCREEN_WIDTH-80+30, 30, 40, 40);
    [saveBar setImage:[UIImage imageNamed:@"add_copy"] forState:UIControlStateNormal];
   
    [saveBar addTarget:self action:@selector(saveCamera) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButtonItem    = [[UIBarButtonItem alloc] initWithCustomView:saveBar];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

- (void)saveCamera
{
    UIImageWriteToSavedPhotosAlbum(self.QRImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error) {
        msg = LocalizationKey(@"savePhotoFailure");
    }
    else {
        msg = LocalizationKey(@"savePhotoSuccess");
    }
    [self.view makeToast:msg duration:1.5 position:CSToastPositionCenter];
}

- (void)popViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.title = LocalizationKey(@"My invitation code");
//    [self rightBarButton];
    
    UIImageView *bgImage = [[UIImageView alloc]init];
    [self.view addSubview:bgImage];
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(-1);
        make.right.bottom.equalTo(0);
    }];
    bgImage.image = ImageName(@"invite_bg");
    
    UIButton *backBtn = [[UIButton alloc]init];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.top.equalTo(SafeAreaNavTopHeight+30);
        make.height.equalTo(40);
        make.width.equalTo(60);
    }];
    [backBtn setImage:ImageName(@"back_white") forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAct) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *navTitleLB = [[UILabel alloc]init];
    [self.view addSubview:navTitleLB];
    [navTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(0);
        make.centerY.equalTo(backBtn);
    }];
    navTitleLB.textColor = [UIColor whiteColor];
    navTitleLB.font = kFont(18);
    navTitleLB.text = LocalizationKey(@"邀请好友");
    
    self.bgView = [UIImageView new];
    [self.view addSubview:self.bgView];
    self.bgView.image =[UIImage imageWithColor:[UIColor blackColor] Size:CGSizeMake(120, 120)];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(0);
        make.top.mas_equalTo(116+SafeAreaTopHeight);
        make.height.width.mas_equalTo(168);
    }];
    
    self.SecretKey = [UILabel new];
    [self.view addSubview:self.SecretKey];
    self.SecretKey.font = [UIFont systemFontOfSize:13];
    self.SecretKey.textColor = [UIColor whiteColor];
    self.SecretKey.textAlignment = NSTextAlignmentCenter;
    self.SecretKey.numberOfLines = 0;

    [self.SecretKey mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(-15);
        make.top.equalTo(self.bgView.mas_bottom).offset(58);
    }];
    
    
    NSString *avatars   = @"http://noahglobal.me/download/register.html";
//    NSString *avatars   = [NSString stringWithFormat:@"%@download/register.html?avatar=%@&lang=cn",HOST,[YLUserInfo shareUserInfo].promotionCode];
    self.SecretKey.text = avatars;
    
    self.QRImage = [UIImageView new];
    [self.bgView addSubview:self.QRImage];
    UIImage * ScannerImag = [self buildQRScanner:self.SecretKey.text];
    self.QRImage.image    = ScannerImag;
    [self.QRImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.top.equalTo(0);
        make.bottom.equalTo(0);
    }];
    
    self.scannQR = [UILabel new];
    [self.view addSubview:self.scannQR];
    self.scannQR.text = LocalizationKey(@"My Invitation Link");
    self.scannQR.font = [UIFont systemFontOfSize:14];
    self.scannQR.textColor     = [UIColor whiteColor];
    self.scannQR.textAlignment = NSTextAlignmentCenter;
    [self.scannQR mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.QRImage).offset(10);
        make.right.equalTo(self.QRImage).offset(-10);
        make.top.equalTo(self.QRImage.mas_bottom).offset(20);
        make.height.equalTo(@30);
    }];
    
    self.CopyContent = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.CopyContent];
    self.CopyContent.layer.cornerRadius  = 4;
    self.CopyContent.backgroundColor = [UIColor colorWithHEX:maincolor];
    [self.CopyContent setTitle:LocalizationKey(@"Copy link") forState:UIControlStateNormal];
    [self.CopyContent setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [self.CopyContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.top.equalTo(self.SecretKey.mas_bottom).offset(25);
        make.height.equalTo(@44);
    }];
    
    @weakify(self);
    [[self.CopyContent rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self.view makeToast:LocalizationKey(@"copyscuuses") duration:1.5 position:CSToastPositionCenter];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = self.SecretKey.text;
    }];
    
    UIImageView *bottomView = [UIImageView new];
    [self.view addSubview:bottomView];
    bottomView.image = [UIImage imageNamed:@""];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(240);
    }];
    
}

- (void)backBtnAct{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIImage *)excludeFuzzyImageFromCIImage: (CIImage *)image size: (CGFloat)size { CGRect extent = CGRectIntegral(image.extent); //通过比例计算，让最终的图像大小合理（正方形是我们想要的）
    CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
    size_t width  = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context     = [CIContext contextWithOptions: nil];
    CGImageRef bitmapImage = [context createCGImage: image fromRect: extent]; CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone); CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    //切记ARC模式下是不会对CoreFoundation框架的对象进行自动释放的，所以要我们手动释放
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    CGColorSpaceRelease(colorSpace);
   
    return [UIImage imageWithCGImage: scaledImage];
}

-(UIImage *)buildQRScanner:(NSString *)url
{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2. 恢复滤镜的默认属性
    [filter setDefaults];
    // 3. 将字符串转换成NSData
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    // 4. 通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKey:@"inputMessage"];
    // 5. 获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    [self excludeFuzzyImageFromCIImage:outputImage size:200];
    // imageView.image = [self excludeFuzzyImageFromCIImage:ciImage size:200];
    
    // 6. 将CIImage转换成UIImage，并放大显示
    return [self excludeFuzzyImageFromCIImage:outputImage size:200];
   // [UIImage imageWithCIImage:outputImage scale:20.0 orientation:UIImageOrientationUp];
}

@end

